package com.hopu.petshop.controller.old;


import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * 生成验证码Servlet
 */
@WebServlet("/code.do")
public class CodeServlet extends HttpServlet {

    public static final String CHARS = "QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm1234567890";
    public static final int WIDTH = 100;
    public static final int HEIGHT = 40;
    public static final int FONT_SIZE = 25;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //创建内存图片
        BufferedImage bufferedImage = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_ARGB);
        //获得图形对象
        Graphics graphics = bufferedImage.getGraphics();
        //设置颜色
        graphics.setColor(Color.GRAY);
        //设置字体
        graphics.setFont(new Font("宋体",Font.ITALIC,FONT_SIZE));
        //填充背景
        graphics.fillRect(0,0, WIDTH,HEIGHT);
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        //随机产生4个字符，绘制到图片上
        for(int i = 0;i < 4;i++){
            char c = CHARS.charAt(random.nextInt(CHARS.length()));
            code.append(c);
            //设置随机颜色
            Color color = new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));
            graphics.setColor(color);
            //绘制字符
            graphics.drawString(String.valueOf(c),i * FONT_SIZE, FONT_SIZE);
        }
        //绘制干扰线条
        for (int i = 0; i < 8; i++) {
            //设置随机颜色
            Color color = new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));
            graphics.setColor(color);
            graphics.drawLine(random.nextInt(WIDTH),random.nextInt(HEIGHT),random.nextInt(WIDTH),random.nextInt(HEIGHT));
        }
        //保存验证码字符串到session中
        req.getSession().setAttribute("code",code.toString());
        //取消浏览器对图片的缓存
        resp.addHeader("Cache-Control","no-cache");
        //通过响应对象的输出流返回图片
        ImageIO.write(bufferedImage,"PNG",resp.getOutputStream());
    }
}
